package com.changgou.file.controller;

import com.changgou.file.FastDfsFile;
import com.changgou.util.FastDfsClient;
import entity.Result;
import entity.StatusCode;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件管理控制器
 *
 * @author mario
 * @version 1.0
 * @date 2020/11/12 14:24
 * @description CrossOrigin：支持跨域
 */
@RestController
@CrossOrigin
public class FileController {
  /**
   * 返回文件信息
   *
   * @param file 页面的文件对象
   * @return
   */
  @PostMapping("/upload")
  public Result<FastDfsFile> upload(@RequestParam(value = "file") MultipartFile file) {
    try {
      FastDfsFile fastdfsfile =
          new FastDfsFile(
              file.getOriginalFilename(),
              file.getBytes(),
              StringUtils.getFilenameExtension(file.getOriginalFilename()));
      String[] upload = FastDfsClient.upload(fastdfsfile);

      fastdfsfile.setContent(null);
      fastdfsfile.setGroup(upload[0]);
      fastdfsfile.setFileName(upload[1]);
      fastdfsfile.setUrl(FastDfsClient.getTrackerUrl() + "/" + upload[0] + "/" + upload[1]);
      return new Result(true, StatusCode.OK, "上传成功", fastdfsfile);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 下载文件
   *
   * @param fastDfsFile 文件对象
   * @return 文件
   */
  @PostMapping("/downFile")
  public File downFile(@RequestBody FastDfsFile fastDfsFile) throws IOException {
    File file = new File(fastDfsFile.getName());
    FileOutputStream fileOutputStream = new FileOutputStream(new File(fastDfsFile.getName()));
    try {
      byte[] bytes = FastDfsClient.downFile(fastDfsFile.getGroup(), fastDfsFile.getFileName());
      fileOutputStream.write(bytes);
      return file;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      fileOutputStream.close();
    }
    return null;
  }

  /**
   * 删除文件
   *
   * @param fastDfsFile 文件信息
   * @return 结果
   */
  @PostMapping("/deleteFile")
  public Result deleteFile(@RequestBody FastDfsFile fastDfsFile) {
    Boolean flag = FastDfsClient.deleteFile(fastDfsFile.getGroup(), fastDfsFile.getFileName());
    String message = flag ? "删除文件成功" : "删除文件失败";
    return new Result(true, StatusCode.OK, "删除文件成功");
  }
}
